package com.jsu.clubmanagementsystem.controller.user;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jsu.clubmanagementsystem.common.BaseResponse;
import com.jsu.clubmanagementsystem.common.ErrorCode;
import com.jsu.clubmanagementsystem.common.PageQueryRequest;
import com.jsu.clubmanagementsystem.common.ResultUtils;
import com.jsu.clubmanagementsystem.exception.BusinessException;
import com.jsu.clubmanagementsystem.model.dto.user.UserAddRequest;
import com.jsu.clubmanagementsystem.model.dto.user.UserLoginRequest;
import com.jsu.clubmanagementsystem.model.dto.user.UserRegisterRequest;
import com.jsu.clubmanagementsystem.model.dto.user.UserUpdateRequest;
import com.jsu.clubmanagementsystem.model.entity.User;
import com.jsu.clubmanagementsystem.model.vo.user.UserListsVO;
import com.jsu.clubmanagementsystem.model.vo.user.UserVO;
import com.jsu.clubmanagementsystem.service.user.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Value("${file.rootPath}")
    private String rootPath;


    @Resource
    private UserService userService;

    /**
     * 用户注册
     *
     * @param registerRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Boolean> userRegister(@RequestBody UserRegisterRequest registerRequest) {
        return ResultUtils.success(userService.userRegister(registerRequest, false));
    }

    /**
     * 用户登录
     *
     * @param loginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<UserVO> userLogin(@RequestBody UserLoginRequest loginRequest, HttpServletRequest request) {
        User user = userService.userLogin(loginRequest, request);
        return ResultUtils.success(UserVO.objToVoAllInfo(user));
    }

    /**
     * 用户登出
     *
     * @param request
     * @return
     */
    @GetMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        return ResultUtils.success(userService.userLogout(request));
    }

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<UserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(UserVO.objToVoAllInfo(user));
    }

    /**
     * 修改用户信息
     *
     * @param updateRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editUser(@RequestBody UserUpdateRequest updateRequest, HttpServletRequest request) {
        if (updateRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }

        User loginUser = userService.getLoginUser(request);
        Long id = updateRequest.getId();
        if (id != null && !id.equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH, "只能修改自己的个人信息");
        }

        if (userService.updateUser(updateRequest)) {
            userService.updateLoginUser(id, request);
        }
        return ResultUtils.success(true);
    }

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    @PostMapping("/get/all")
    public BaseResponse<Page<UserListsVO>> getAllUser(@RequestBody PageQueryRequest page) {
        return ResultUtils.success(userService.getAllUser(page));
    }

    @DeleteMapping("/delete")
    @Transactional
    public BaseResponse<Boolean> deleteUsers(@RequestParam List<Long> userIds){
        userIds.forEach(e->{
            if(!userService.removeUser(e)){

                throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除失败");
            }
        });
        return ResultUtils.success(true);
    }

    @PostMapping(value="/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public BaseResponse<User> addUser(@RequestPart("add") @Valid UserAddRequest add, @RequestPart("avatar") MultipartFile avatar) throws IOException {
        //生成uuid
        String uuid= UUID.randomUUID().toString();
        //上传头像
        try(FileOutputStream out=new FileOutputStream(rootPath+uuid+"_"+avatar.getOriginalFilename())){
            out.write(avatar.getBytes());
            String fileUrl="http://localhost:8080/api/user/get/avatar/";
            add.setUserAvatar(fileUrl+uuid+"_"+avatar.getOriginalFilename());
        }catch(IOException e){
            throw new BusinessException("图片上传失败", ErrorCode.OPERATION_ERROR.getCode());
        }
        return ResultUtils.success(userService.addUsers(add));
    }


    /**
     * 头像路径映射
     * @param file
     */
    @GetMapping("/get/avatar/{file}")
    public void getAvatar(@PathVariable String file, HttpServletResponse http) {
        log.info("{}",file);
        File avatar=new File(rootPath+file);
        try(FileInputStream inputStream=new FileInputStream(avatar)){
            ServletOutputStream out=http.getOutputStream();
            out.write(inputStream.readAllBytes());
            out.flush();
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.NOT_FOUND,"图片不存在");
        }
    }
}
